import { createRouter, createWebHistory } from 'vue-router'
import useStore from '@/store/index'
import {ElMessage} from "element-plus";

const routes = [
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/HomeView.vue'),
    redirect:'/content',
    children:[
      {
        path: '/content',
        name: 'content',
        component: () => import('@/components/modules/content/Content.vue'),
      },
      {
        path: '/user',
        name: 'user',
        component: () => import('@/components/modules/user/index.vue'),
      },
      {
        path: '/car',
        name: 'car',
        component: () => import('@/components/modules/car/index.vue'),
      },
      {
        path: '/category',
        name: 'category',
        component: () => import('@/components/modules/category/index.vue'),
      },
      {
        path: '/goods',
        name: 'goods',
        component: () => import('@/components/modules/goods/index.vue'),
      },
      {
        path: '/order',
        name: 'order',
        component: () => import('@/components/modules/order/index.vue'),
      },
      {
        path: '/chat',
        name: 'chat',
        component: () => import('@/components/modules/chat/index.vue'),
      },
    ]
  },
  {
    path: '/user/:username',
    name: 'user_page',
    component: () => import('@/components/modules/user/UserPage.vue'),
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/about',
    name: 'about',
    component: () => import( '../views/AboutView.vue')
  },
  // 配置404页面
  {
    path: '/:pathMatch(.*)*',
    name: '404',
    component: () => import('../views/NotFound.vue'),
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 拿到用户对象信息
  const {userStore} = useStore()
  const user = userStore.user
  const hasUser = user && user.id
  // 定义无需登录的路由
  const noPermissionPaths = ['/login', '/register', '/404']
  // 用户没登录,  假如你当前跳转login页面，然后login页面没有用户信息，这个时候你再去往 login页面跳转，就会发生无限循环跳转
  if (!hasUser && !noPermissionPaths.includes(to.path)) {
    // 获取缓存的用户数据
    // 如果to.path === '/login' 的时候   !noPermissionPaths.includes(to.path) 是返回 false的，也就不会进 next("/login")
    ElMessage.info('不好意思，您还未登录')
    next("/login")
  } else {
    if (!to.matched.length) {
      next('/404')
    } else {
      next()
    }
  }
})

export default router
